﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace YTSK.FrmKP
{
    public partial class FrmLogin : Form
    {
        public FrmLogin()
        {
            try
            {
                InitializeComponent();
                this.Icon = YTSK.Properties.Resources.Fly;
                RegistryLoad();
                this.btLogin.Click += Login;
                this.btCancel.Click += Cancel;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
        }


        #region 从注册表读入网址，用户名，密码等信息
        /// <summary>
        /// 初始化时从注册表读入网址，用户名，密码等信息
        /// </summary>
        private void RegistryLoad()
        {
            ServerConfig.ServerAddress = Common.HandleRegistry.readKey("tbaddress", "login");
            this.tbAddress.Text = ServerConfig.ServerAddress;
            int icheck = Common.HandleRegistry.readKey("cbsave", "login").ObjToInt();
            if (icheck == 1)
            {
                ServerConfig.UserName = Common.HandleRegistry.readKey("tbUserNameCustomer", "login");
                this.tbUserName.Text = ServerConfig.UserName;
                ServerConfig.PassWord = Common.HandleRegistry.readKey("tbPasswordCustomer", "login");
                this.tbPassword.Text = ServerConfig.PassWord;
                this.cbSave.Checked = true;
            }
            else
            { this.cbSave.Checked = false; }
        }
        private void RegistrySave()
        {

            ServerConfig.ServerAddress = this.tbAddress.Text.Trim();
            ServerConfig.UserName = this.tbUserName.Text.Trim();
            ServerConfig.PassWord = this.tbPassword.Text.Trim();

            Common.HandleRegistry.saveKey("tbaddress", ServerConfig.ServerAddress, "login");
            int icheck = 0;
            if (this.cbSave.Checked) { icheck = 1; }
            Common.HandleRegistry.saveKey("cbsave", icheck.ToString(), "login");
            if (icheck == 1)
            {
                Common.HandleRegistry.saveKey("tbUserNameCustomer", ServerConfig.UserName, "login");
                Common.HandleRegistry.saveKey("tbPasswordCustomer", ServerConfig.PassWord, "login");
            }
        }
        #endregion


        private void Login(object sender, EventArgs e)
        {
            try
            {
                RegistrySave();
                var err= ServerConfig.Login();
                if (err.Length > 0) { MessageBox.Show(err); }
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("出现异常" + ex.Message + ex.StackTrace,"错误",MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void Cancel(object sender, EventArgs e)
        { this.Close(); }
    }
}
